package mod_logid

import (
	"crypto/rand"
	"encoding/hex"
	"ezcloud/gw/pkg/route"
)

const (
	HeaderRequestId = "X-Request-Id"
)

func ModGenLogId(context *route.RouteContext, chain route.RouteFilterChain) {
	id := context.OrigRequest.Header.Get(HeaderRequestId)
	if id != "" {
		context.RequestId = id
	} else {
		context.RequestId = genLogId()
		context.RequestHeader.Add(HeaderRequestId, context.RequestId)
	}

	chain.Filter(context)
}

func genLogId() string {
	b := make([]byte, 16)
	_, err := rand.Read(b)
	if err != nil {
		return ""
	}
	return hex.EncodeToString(b)
}
